package network;/*
 *@ 代阳敲的专属代码
 **/

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;

public class  UdpEchoClient {

    private DatagramSocket socket;
    //客户端要发给那个服务端的IP
    private String sererIp;
    //客户端要发给那个服务端的端口
    private int serverPort;


    //创建客户端,并指定要发那个服务端的IP和端口
    public UdpEchoClient( String sererIp, int serverPort) throws SocketException {
        this.sererIp = sererIp;
        this.serverPort = serverPort;
        this.socket=new DatagramSocket();

    }
    public  void  strat() throws IOException {
        Scanner scanner =new Scanner(System.in);
        System.out.println("客户端启动");
        while(true) {
            System.out.println("->");
            String request=scanner.next();
            //打包客户端要发送的数据，参数（转化数据，从那开始，结束长度，服务端的地址）
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    new InetSocketAddress(sererIp,serverPort));
            //发送
            socket.send(requestPacket);

            //打包接收服务端的传输的数据
            DatagramPacket responsePacket =new DatagramPacket(new byte[1024],1024);
            //接收服务端的数据
            socket.receive(responsePacket);
            String response =new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);

        }
    }
    public static void main(String[] args) throws IOException {
//        UdpEchoServer udpEchoServer=new UdpEchoServer(8080);
//        udpEchoServer.start();
        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.strat();
    }
}